package cn.com.gome.sn.web.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;

import cn.com.gome.frame.logger.HLogger;
import cn.com.gome.frame.logger.LoggerManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import cn.com.gome.frame.cache.ApplicationCache;

@Service
public class WEBTempleteLoader {

	private static HLogger logger = LoggerManager.getLoger("WEBTempleteLoader");
	
	@Value("#{SN_web['WEBTemplete_BASEHEAD']}")
	private String WEBTemplete_BASEHEAD_;
	
	@Value("#{SN_web['WEBTemplete_BASETAIL']}")
	private String WEBTemplete_BASETAIL_;
	
	@Value("#{SN_web['WEBTemplete_HEAD']}")
	private String WEBTemplete_HEAD_;

	private static String WEBTemplete_BASEHEAD=null;
	private static String WEBTemplete_BASETAIL=null;
	private static String WEBTemplete_HEAD=null;
	
	private static String WEBTemplete_BASEHEAD_RS = "";
	private static String WEBTemplete_BASETAIL_RS = "";
	private static String WEBTemplete_HEAD_RS = "";
	
	@PostConstruct
	public synchronized void init(){
		WEBTemplete_BASEHEAD = this.WEBTemplete_BASEHEAD_;
		WEBTemplete_BASETAIL = this.WEBTemplete_BASETAIL_;
		WEBTemplete_HEAD = this.WEBTemplete_HEAD_;
		freshResources();
		new Thread(new Runnable() {
			int i = 0;
			public void run() {
				while(true){
					try {
						freshResources();
						if(i<=17280){
							//启动后一天之内
							Thread.sleep(5000);//每五秒钟刷新一次缓存
						}else{
							//启动后一天之后
							Thread.sleep(60*1000*5);//每五分钟刷新一次缓存
						}
					} catch (InterruptedException e) {
						logger.error("缓存刷新异常",e);
					}
				}
			}
		}).start();
	}
	
	public static String parse(String str){
		Map<String, String> s = new HashMap<String, String>();
		W:for(int i=0;i<str.length();i++){
			try{
				int i_$ = str.indexOf("$",i);
				int i_LHK = str.indexOf("{",i_$);
				int i_props = str.indexOf("props",i_LHK);
				int i_LK = str.indexOf("(",i_props);
				int i_RK = str.indexOf(")",i_LK);
				int i_RHK = str.indexOf("}",i_RK);
				
				if(i_$>0&&i_LHK>0&&i_props>0&&i_props>0&&i_LK>0&&i_RK>0&&i_RHK>0){
					//如果都找到了这些token
					//判断是否有空格
					if(i_LHK-i_$>1){
						for(int ii = i_$+1;ii<i_LHK;ii++){
							if(str.charAt(ii)!=' '){
								i=ii;
								continue W;
							}
						}
					}
					if(i_props-i_LHK>1){
						for(int ii = i_LHK+1;ii<i_props;ii++){
							if(str.charAt(ii)!=' '){
								i=ii;
								continue W;
							}
						}
					}
					if(i_LK-i_props>5){
						for(int ii = i_props+5;ii<i_LK;ii++){
							if(str.charAt(ii)!=' '){
								i=ii;
								continue W;
							}
						}
					}
					if(i_RHK-i_RK>1){
						for(int ii = i_RK+1;ii<i_RHK;ii++){
							if(str.charAt(ii)!=' '){
								i=ii;
								continue W;
							}
						}
					}
					
					String propertyName = str.substring(i_LK+1,i_RK).trim();
					propertyName = propertyName.substring(1,propertyName.length()-1);//去除单引号
					
					String propertyToken = str.substring(i_$,i_RHK+1).trim();
					String value  = ApplicationCache.getInstance().getStr(propertyName);
					s.put(propertyToken, value);
					i=i_RK;
				}	
			}catch(Exception e){
				logger.error("解析异常",e);
			}
		}
		for(Entry<String, String> e : s.entrySet()){
			String key = e.getKey();
			String value = (e.getValue()==null?"":e.getValue());
			str = str.replace(key, value);
		}
		return str;
	}
	
	public synchronized static void freshResources(){
		for(int i = 0;i<5;i++){
			try{
				URL u = new URL(WEBTemplete_BASEHEAD);
				UrlResource ur = new UrlResource(u);
				InputStream in = ur.getInputStream();
				byte[] s = new byte[1024];
				ByteArrayOutputStream bao = new ByteArrayOutputStream();
				int c = 0;
				while((c=in.read(s))>=0){
					bao.write(s,0,c);
				}
				in.close();
				String tmp =  new String(bao.toByteArray(),"UTF-8");
				WEBTemplete_BASEHEAD_RS = tmp;
				ApplicationCache.getInstance().put("WEBTemplete_BASEHEAD_RS", parse(WEBTemplete_BASEHEAD_RS));
				break;
			}catch(Exception e){
				logger.error("公共头部刷新异常", e);
			}
		}
		for(int i = 0;i<5;i++){
			try{
				URL u = new URL(WEBTemplete_BASETAIL);
				UrlResource ur = new UrlResource(u);
				InputStream in = ur.getInputStream();
				byte[] s = new byte[1024];
				ByteArrayOutputStream bao = new ByteArrayOutputStream();
				int c = 0;
				while((c=in.read(s))>=0){
					bao.write(s,0,c);
				}
				in.close();
				String tmp =  new String(bao.toByteArray(),"UTF-8");
				WEBTemplete_BASETAIL_RS = tmp;
				ApplicationCache.getInstance().put("WEBTemplete_BASETAIL_RS", parse(WEBTemplete_BASETAIL_RS));
				break;
			}catch(Exception e){
				logger.error("公共头部刷新异常", e);
			}
		}
		for(int i = 0;i<5;i++){
			try{
				URL u = new URL(WEBTemplete_HEAD);
				UrlResource ur = new UrlResource(u);
				InputStream in = ur.getInputStream();
				byte[] s = new byte[1024];
				ByteArrayOutputStream bao = new ByteArrayOutputStream();
				int c = 0;
				while((c=in.read(s))>=0){
					bao.write(s,0,c);
				}
				in.close();
				String tmp =  new String(bao.toByteArray(),"UTF-8");
				WEBTemplete_HEAD_RS = tmp;
				ApplicationCache.getInstance().put("WEBTemplete_HEAD_RS", parse(WEBTemplete_HEAD_RS));
				break;
			}catch(Exception e){
				logger.error("公共头部刷新异常", e);
			}
		}
	}
	public static void main(String[] args) {
		synchronized (WEBTempleteLoader.class){
			WEBTemplete_BASEHEAD = "http://jr.gomein.net.cn/finance/WEBTemplete/WEBTemplete_BASEHEAD/WEBTemplete_BASEHEAD.rs";
			WEBTemplete_BASETAIL = "http://jr.gomein.net.cn/finance/WEBTemplete/WEBTemplete_BASETAIL/WEBTemplete_BASETAIL.rs";
			WEBTemplete_HEAD = "http://jr.gomein.net.cn/finance/WEBTemplete/WEBTemplete_HEAD/WEBTemplete_HEAD.rs";
			freshResources();
		}
	}
}
